from flask import current_app,jsonify
from flask_restful import reqparse
from views.admin import BaseView
from models.model import PoetryModel,db

import json
import requests
from bs4 import BeautifulSoup
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36'  #伪装成浏览器
}



class JoinView(BaseView):
    def post(self,id):
        url = 'https://so.gushiwen.cn/shiwens/default.aspx?page=' + str(id) + '&tstr=&astr=&cstr=%E5%94%90%E4%BB%A3&xstr='
        r = requests.get(url, headers=headers)
        r.encoding = "UTF-8"
        soup = BeautifulSoup(r.text, 'html.parser')
        td = soup.find_all('div', class_='cont')
        for i in td:
            zi = {}
            name = i.find_all('p')
            name1 = i.find_all('p', class_='source')
            for x in name:
                if x.a != None:
                    if x.a.b != None:
                        zi1 = {'title':x.a.b.string}
                        zi.update(zi1)
            for q in name1:
                zi2 = {'author':q.a.string}
                zi.update(zi2)

            neirong = i.find_all('div',class_='contson')
            for w in neirong:
                shan = str(w).replace('<br/>', '')
                shan1 = shan.replace('<p>','')
                shan2 = shan1.replace('</p>', '')
                cheng = BeautifulSoup(shan2)
                chong = cheng.find_all('div', class_='contson')
                for e in chong:
                    shan3 = str(e.string).replace('\r\n','')
                    shan4 = shan3.replace('\u3000\u3000','')
                    shan5 = shan4.replace('\n','')
                    zi3 = {'content': shan5}
                    zi.update(zi3)

            if zi != {}:
                p = PoetryModel(
                    title=zi.get('title'),
                    author=zi.get('author'),
                    content=zi.get('content'),
                )
                db.session.add(p)
                db.session.commit()
                print('??>>>>>>>>',zi)



# 获取古诗
class PoetryView(BaseView):
    def get(self):
        poetry = PoetryModel.query.all()
        poetry_list = []

        for i in poetry:
            poetry_list.append({
                'pid':i.pid,
                'title':i.title,
                'author':i.author,
                'content':i.content,
            })

        return jsonify({
            'code':200,
            'msg':'获取成功',
            'data':poetry_list,
        })


# http://127.0.0.1:5000/admin/join



